﻿using LPP.Entity;
using LPP.Entity.Booking;
using LPP.Entity.BusEntitys;
using LPP.Entity.Logs;
using LPP.Entity.Media;
using LPP.Entity.Notification;
using LPP.Entity.Statistic;
using Microsoft.EntityFrameworkCore;
using LPP.Entity.Orders;
using LPP.Entity.AppUser;
using LPP.Entity.Payment;
using LPP.Entity.Addresses;
using LPP.Entity.Work;
using LPP.Entity.ChatMessage;
using LPP.Entity.PaymentRecord;

namespace LPP.EntityFrameworkCore
{
    public class SqlDbContext:DbContext
    {
        /// <summary>
        /// 数据库链接字符串
        /// </summary>
        /// <param name="options"></param>
        public SqlDbContext(DbContextOptions<SqlDbContext> options)
        : base(options)
        {

        }
        public DbSet<PaymentRecord> PaymentRecords { get; set; }
        //业务表
        public virtual DbSet<Picture> Pictures { get; set; }//图片表
       // 媒体表
        public virtual DbSet<Image> Images { get; set; }
        public virtual DbSet<Video> Videos { get; set; }
        public virtual DbSet<Share> Shares { get; set; }
        public virtual DbSet<Favorite> Favorites { get; set; }
        public DbSet<Media> Media { get; set; }
        //预约表
        public DbSet<Booking> Bookings { get; set; }
        //统计与日志表
        public DbSet<Statistic> Statistics { get; set; }
        public DbSet<Logs> Logs { get; set; }
        //通知表
        public DbSet<Notification> Notifications { get; set; }

        public DbSet<SmsVerification> SmsVerifications { get; set; }

        public DbSet<Order> Orders { get; set; } // 假设Order是你的订单实体类
        public DbSet<UserReview> UserReviews { get; set; }
        //用户表和联系人表
        public DbSet<Users> Users { get; set; }
        public DbSet<Contact> Contacts { get; set; }

        public DbSet<OrderDetail> OrderDetails { get; set; }
        public DbSet<Payment> Payments { get; set; }
        public DbSet<Address> Addresses { get; set; }//地址表
        public DbSet<Worker> Workers { get; set; }
        public DbSet<ChatMessage> ChatMessages { get; set; }
       
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // 定义 Order 与 OrderDetail 的关系
            modelBuilder.Entity<Order>()
                .HasMany(o => o.OrderDetails)
                .WithOne(od => od.Order)
                .HasForeignKey(od => od.OrderID);

            // 定义 UserReview 实体
            modelBuilder.Entity<UserReview>()
                .HasKey(r => r.ReviewID);

            modelBuilder.Entity<UserReview>()
                .Property(u => u.UserID)
                .IsRequired();

            modelBuilder.Entity<UserReview>()
                .Property(r => r.ReviewDate)
                .IsRequired();

            // 定义 Users 实体
            modelBuilder.Entity<Users>()
                .HasKey(u => u.UserID); // 明确指定主键

            modelBuilder.Entity<Users>()
                .HasMany(u => u.Orders)
                .WithOne(o => o.User)
                .HasForeignKey(o => o.UserID);

            modelBuilder.Entity<Users>()
                .Property(e => e.CreatedAt)
                .HasColumnType("datetime2"); // 确保使用 datetime2 类型

            // 用户与地址的关系
            modelBuilder.Entity<Address>()
                .HasOne(a => a.Users)  // 一个地址只能属于一个用户
                .WithMany(u => u.Address)  // 一个用户可以有多个地址
                .HasForeignKey(a => a.UserID)
                .OnDelete(DeleteBehavior.Cascade); // 启用级联删除

            // 定义 Order 实体的金额属性
            modelBuilder.Entity<Order>()
                .Property(o => o.Amount)
                .HasColumnType("decimal(18, 2)"); // 根据需要调整精度

            // 定义 OrderDetail 实体的 UnitPrice 属性
            modelBuilder.Entity<OrderDetail>()
                .Property(od => od.UnitPrice)
                .HasColumnType("decimal(18, 2)");

            // 定义 Payment 实体的 Amount 属性
            modelBuilder.Entity<Payment>()
                .Property(p => p.Amount)
                .HasColumnType("decimal(18, 2)");

            // 定义 Worker 实体
            modelBuilder.Entity<Worker>()
                .HasKey(w => w.WorkerID);

            modelBuilder.Entity<ChatMessage>()
          .HasOne(m => m.Sender)
          .WithMany()
          .HasForeignKey(m => m.SenderId)
          .OnDelete(DeleteBehavior.Restrict);

            modelBuilder.Entity<ChatMessage>()
                .HasOne(m => m.Receiver)
                .WithMany()
                .HasForeignKey(m => m.ReceiverId)
                .OnDelete(DeleteBehavior.Restrict);

            modelBuilder.Entity<OrderDetail>(entity =>
            {
                entity.HasKey(e => e.OrderDetailID);

                // 配置金额相关字段
                entity.Property(e => e.TotalPrice)
           .HasComputedColumnSql("[UnitPrice] * [Quantity]", stored: true)
           .HasColumnType("decimal(18,2)");

                entity.Property(e => e.UnitPrice)
                      .HasColumnType("decimal(18,2)")
                      .IsRequired();

                // 配置评分字段
                entity.Property(e => e.Rating)
                      .HasColumnType("decimal(3,1)");

                // 配置与 Order 的关系
                entity.HasOne(e => e.Order)
                      .WithMany(o => o.OrderDetails)
                      .HasForeignKey(e => e.OrderID)
                      .OnDelete(DeleteBehavior.Cascade);

                // 配置与 Worker 的关系
                entity.HasOne(e => e.Worker)
                      .WithMany(w => w.OrderDetails)
                      .HasForeignKey(e => e.WorkerID)
                      .OnDelete(DeleteBehavior.Restrict);

                // 配置时间字段
                entity.Property(e => e.AssignedAt)
                      .HasColumnType("datetime2")
                      .IsRequired();

                entity.Property(e => e.CompletedAt)
                      .HasColumnType("datetime2");

                modelBuilder.Entity<OrderDetail>()
                    .Property(od => od.PlatformIncome)
                    .HasPrecision(18, 2);

                modelBuilder.Entity<OrderDetail>()
                    .Property(od => od.WorkerIncome)
                    .HasPrecision(18, 2);
                // 配置 OrderDetail 的 decimal 属性
                modelBuilder.Entity<OrderDetail>()
                    .Property(od => od.CommissionRate)
                    .HasPrecision(18, 2);

       
            });

            // 配置 SmsVerification 实体
            modelBuilder.Entity<SmsVerification>(entity =>
            {
                entity.HasKey(e => e.Id);
                
                entity.Property(e => e.PhoneNumber)
                    .IsRequired()
                    .HasMaxLength(20);
                    
                entity.Property(e => e.Code)
                    .IsRequired()
                    .HasMaxLength(10);
                    
                entity.Property(e => e.CreatedAt)
                    .IsRequired()
                    .HasColumnType("datetime2");
            });
        }
 
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            // 只在查询统计数据时启用跟踪
            optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
            base.OnConfiguring(optionsBuilder);
        }
    }
}
